package com.zzzyh.forumsystemclient.services.impl;

import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.fastjson.JSON;
import com.zzzyh.forumsystemclient.dao.ChatMsgMapper;
import com.zzzyh.forumsystemclient.dao.ChatRoomMapper;
import com.zzzyh.forumsystemclient.model.ChatMsg;
import com.zzzyh.forumsystemclient.model.ChatRoom;
import com.zzzyh.forumsystemclient.model.UserFriendChatroom;
import com.zzzyh.forumsystemclient.services.IChatService;
import com.zzzyh.forumsystemclient.webSocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class ChatServiceImpl implements IChatService {
    @Autowired
    private ChatMsgMapper chatMsgMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private DashScopeAIService dashScopeAIService;
    @Autowired
    private ChatRoomMapper chatRoomMapper;

    @Override
    public List<ChatMsg> list(Integer pageNum, Integer pageSize,Integer roomId) {
        return chatMsgMapper.list((pageNum-1)*pageSize, pageSize, roomId);
    }

    @Override
    public Integer total() {
        return chatMsgMapper.total();
    }

    @Override
    public void send(ChatMsg chatMsg) {
        log.info("发送消息：{}", chatMsg);
        chatMsgMapper.insertSelective(chatMsg);
        if (chatMsg.getIsgroup() == 1){
//            webSocketServer.sendAllMessage(JSON.toJSONString(chatMsg));
            webSocketServer.sendAllMessageExceptMe(JSON.toJSONString(chatMsg), String.valueOf(chatMsg.getSenderId()));

            if (chatMsg.getContent() != null && chatMsg.getContent().contains("@robot")){
//                String aiResponse = generateAIResponse(chatMsg.getContent());
                String aiResponse = null;
                try {
                    aiResponse = dashScopeAIService.appCall(chatMsg.getContent());
                } catch (NoApiKeyException e) {
                    throw new RuntimeException(e);
                } catch (InputRequiredException e) {
                    throw new RuntimeException(e);
                }
                // 创建AI回复消息
                ChatMsg aiMsg = new ChatMsg();
                aiMsg.setSenderId(2); // 2为robot的ID
                aiMsg.setContent(aiResponse);
                aiMsg.setCreateTime(new java.util.Date());
                aiMsg.setRoomId(chatMsg.getRoomId());
                aiMsg.setType("text");

                // 发送AI回复
                chatMsgMapper.insertSelective(aiMsg);
                webSocketServer.sendAllMessage(JSON.toJSONString(aiMsg));
            }
        }else if (chatMsg.getIsgroup() == 2){
            if (chatMsg.getToUserId() == 2){
            webSocketServer.sendMessageByUserId(JSON.toJSONString(chatMsg), String.valueOf(chatMsg.getSenderId()));
                // 发送个机器人
                String aiResponse = null;
                try {
                    aiResponse = dashScopeAIService.appCall(chatMsg.getContent());
                } catch (NoApiKeyException e) {
                    throw new RuntimeException(e);
                } catch (InputRequiredException e) {
                    throw new RuntimeException(e);
                }
                ChatMsg aiMsg = new ChatMsg();
                aiMsg.setSenderId(2);
                aiMsg.setContent(aiResponse);
                aiMsg.setCreateTime(new java.util.Date());
                aiMsg.setRoomId(chatMsg.getRoomId());
                aiMsg.setType("text");
                chatMsgMapper.insertSelective(aiMsg);
                webSocketServer.sendMessageByUserId(JSON.toJSONString(aiMsg), String.valueOf(chatMsg.getSenderId()));
            }else {
                webSocketServer.sendMessageByUserId( JSON.toJSONString(chatMsg),String.valueOf(chatMsg.getToUserId()));
//                webSocketServer.sendMessageByUserId(JSON.toJSONString(chatMsg), String.valueOf(chatMsg.getSenderId()));
            }
        }

    }

    private String generateAIResponse(String content) {
        try {
            // 移除@robot标识，只保留实际内容
            String cleanContent = content.replace("@robot", "").trim();

            // 调用DashScopeAI服务生成回复
            String aiResponse = dashScopeAIService.chatWithAI(cleanContent);

            if (aiResponse != null && !aiResponse.trim().isEmpty()) {
                return aiResponse.trim();
            } else {
                return "抱歉，我暂时无法回答这个问题。";
            }
        } catch (Exception e) {
            log.error("调用AI服务生成回复失败: {}", e.getMessage(), e);
            return "抱歉，我现在有点忙，请稍后再试。";
        }
    }

    @Override
    public List<Integer> getFriendsList(Integer userID) {
        log.info("获取用户好友列表：{}", userID);
        List<Integer> friendsList = chatMsgMapper.getFriendsList(userID);
        // 加入机器人
        log.info("friendsList: {}", friendsList);
        friendsList.add(2);
        return friendsList;
    }

    @Override
    public List<ChatRoom> rooms(Integer userID) {
        List<Integer> roomsId = chatMsgMapper.getRoomsIdList(userID);
        // 添加默认房间
        roomsId.add(1);
        roomsId.addAll(chatRoomMapper.getFriendChatroomsByUserId(userID));
        log.info("roomsId: {}", roomsId);
        List<ChatRoom> roomList = chatMsgMapper.getRooms(roomsId);
        log.info("roomList: {}", roomList);
        for (ChatRoom room : roomList){
            ChatMsg lastMsg = chatMsgMapper.getLastMsg(room.getId());
            log.info("lastMsg: {}", lastMsg);
            if (lastMsg != null){
                room.setLastMessage(lastMsg.getContent());
                room.setLastTime(lastMsg.getCreateTime());
                room.setType(lastMsg.getType());
            }

        }
        return roomList;
    }

    @Override
    public ChatRoom roomWithFriend(Integer userId, Integer friendId) {
        Integer roomId =chatMsgMapper.getRoomIdWithFriend(userId, friendId);
        if (roomId == null){
            // 创建房间
            ChatRoom chatRoom = new ChatRoom();
            chatRoom.setIsgroup(2);
//            chatRoom.setName(userId+"-" + friendId+"的聊天室");
            chatRoom.setName(chatRoomMapper.getNameById(userId)+"-" + chatRoomMapper.getNameById(friendId)+"的聊天室");
            chatRoom.setContent(userId + "-" + friendId);
            chatRoom.setUserId(Long.valueOf(userId));
            chatRoomMapper.insertSelective(chatRoom);
            UserFriendChatroom userFriendChatroom = new UserFriendChatroom();
            userFriendChatroom.setUser1Id(userId);
            userFriendChatroom.setUser2Id(friendId);
            userFriendChatroom.setRoomId(chatRoom.getId());
            userFriendChatroom.setState(1);
            chatRoomMapper.insertFriendChatroom(userFriendChatroom);
            roomId = Math.toIntExact(chatRoom.getId());
        }
        return chatRoomMapper.selectByPrimaryKey(Long.valueOf(roomId));
    }

    @Override
    public ChatMsg getLastMsg(Long roomId) {
        return chatMsgMapper.getLastMsg(roomId);
    }

    @Override
    public void recallMsg(Integer id) {
        chatMsgMapper.recallMsg(id);
    }

    @Override
    public Integer getUnreadCount(Long roomId, Integer userID) {
        Integer unreadCount = chatMsgMapper.getUnreadCount(roomId, userID);
        return unreadCount == null ? 0 : unreadCount;
    }

    @Override
    public void updateUnreadCount(Long roomId, Integer userId,Integer unreadCount) {
        if (chatRoomMapper.existUnreadMsg(roomId, userId) != null){
            log.info("存在未读消息");
            chatRoomMapper.updateUnreadCount(roomId, userId, unreadCount);

        }else{
            log.info("不存在未读消息");
            chatRoomMapper.insertUnreadMsg(roomId, userId, unreadCount);

        }
    }

    @Override
    public List<Integer> getAdminFriendsList() {

        return  chatMsgMapper.getAdminFriendsList();
    }
}
